<template>
  <div class="financial-module">
    
    <!-- API 控制区域 -->
    <div class="api-controls">
      <div class="card">
        <h2 class="subtitle">API 数据设置</h2>
        
        <!-- API 时间选择器 -->
        <div class="form-group">
          <label>时间范围</label>
          <div class="time-selector">
            <select v-model="apiTimeFilter.type" @change="resetApiTimeFilter">
              <option value="month">月份</option>
              <option value="quarter">季度</option>
              <option value="year">年份</option>
            </select>
            
            <select v-if="apiTimeFilter.type === 'month'" v-model="apiTimeFilter.year">
              <option v-for="year in availableYears" :value="year">{{ year }}年</option>
            </select>
            <select v-if="apiTimeFilter.type === 'month'" v-model="apiTimeFilter.month">
              <option v-for="month in availableMonths" :value="month">{{ month }}月</option>
            </select>
            
            <select v-if="apiTimeFilter.type === 'quarter'" v-model="apiTimeFilter.year">
              <option v-for="year in availableYears" :value="year">{{ year }}年</option>
            </select>
            <select v-if="apiTimeFilter.type === 'quarter'" v-model="apiTimeFilter.quarter">
              <option value="1">第一季度</option>
              <option value="2">第二季度</option>
              <option value="3">第三季度</option>
              <option value="4">第四季度</option>
            </select>
            
            <select v-if="apiTimeFilter.type === 'year'" v-model="apiTimeFilter.year">
              <option v-for="year in availableYears" :value="year">{{ year }}年</option>
            </select>
          </div>
        </div>
        
        <button @click="fetchApiData" :disabled="loading">
          {{ loading ? '加载中...' : '获取数据' }}
        </button>
      </div>
    </div>
    
    <!-- 报表显示区域 -->
    <div class="report-container">
      <div class="card">
        <div class="report-header">
          <h2 class="subtitle">
            财务报表 - 
            <span class="report-period">
              {{ getApiPeriodDisplay() }}
            </span>
          </h2>
          <div class="status-tag" :class="reportData.profitStatus">
            {{ reportData.profitStatus === 'profit' ? '盈利' : '亏损' }}
          </div>
        </div>
        
        <div class="report-summary">
          <div class="summary-item">
            <div class="item-label">总收入</div>
            <div class="item-value">{{ formatCurrency(reportData.totalIncome) }}</div>
          </div>
          <div class="summary-item">
            <div class="item-label">总成本</div>
            <div class="item-value">{{ formatCurrency(reportData.totalCost) }}</div>
          </div>
          <div class="summary-item" :class="reportData.profitStatus">
            <div class="item-label">总利润</div>
            <div class="item-value">{{ formatCurrency(reportData.totalProfit) }}</div>
          </div>
        </div>
        
        <h3 class="sub-subtitle">收入明细</h3>
        <div class="table-responsive">
          <table class="details-table">
            <thead>
              <tr>
                <th>类别</th>
                <th>金额</th>
                <th>占比</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in reportData.incomeDetails" :key="index">
                <td>{{ item.category }}</td>
                <td>{{ formatCurrency(item.amount) }}</td>
                <td>{{ item.percentage }}%</td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div class="chart-container">
          <canvas id="profitChart"></canvas>
        </div>
      </div>
    </div>
    
    <!-- API 数据明细 -->
    <div v-if="apiSalesData.length > 0" class="api-details">
      <div class="card">
        <h3 class="subtitle">销售与成本明细</h3>
        
        <div class="details-tabs">
          <button 
            :class="{ active: activeTab === 'sales' }" 
            @click="activeTab = 'sales'">
            销售明细
          </button>
          <button 
            :class="{ active: activeTab === 'costs' }" 
            @click="activeTab = 'costs'">
            成本明细
          </button>
        </div>
        
        <div v-if="activeTab === 'sales'" class="tab-content">
          <div class="table-responsive">
            <table class="details-table">
              <thead>
                <tr>
                  <th>订单ID</th>
                  <th>订单日期</th>
                  <th>金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(order, index) in apiSalesData" :key="index">
                  <td>{{ order.orderId }}</td>
                  <td>{{ order.orderDate }}</td>
                  <td>{{ formatCurrency(order.totalAmount) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <div class="summary">
            <span class="label">销售订单总数:</span>
            <span class="value">{{ apiSalesData.length }}</span>
          </div>
        </div>
        
        <div v-if="activeTab === 'costs'" class="tab-content">
          <div class="table-responsive">
            <table class="details-table">
              <thead>
                <tr>
                  <th>供应商ID</th>
                  <th>供应商名称</th>
                  <th>进货日期</th>
                  <th>金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(cost, index) in apiCostData" :key="index">
                  <td>{{ cost.supplierId }}</td>
                  <td>{{ cost.supplierName }}</td>
                  <td>{{ cost.purchaseDate }}</td>
                  <td>{{ formatCurrency(cost.totalCost) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <div class="summary">
            <span class="label">供应商总数:</span>
            <span class="value">{{ apiCostData.length }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle"></i> {{ errorMessage }}
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';
import axios, { AxiosError } from 'axios';
import { Chart, registerables } from 'chart.js';
import type { TooltipItem } from 'chart.js';
Chart.register(...registerables);

// 数据类型定义
interface IncomeItem {
  category: string;
  amount: number;
  percentage: number;
}

interface ReportData {
  totalIncome: number;
  totalCost: number;
  totalProfit: number;
  incomeDetails: IncomeItem[];
  profitStatus: 'profit' | 'loss';
}

// API数据类型
interface SalesOrder {
  orderId: string;
  orderDate: string;
  totalAmount: number;
  items?: {
    productId: string;
    productName: string;
    quantity: number;
    price: number;
  }[];
}

interface SupplierCost {
  supplierId: string;
  supplierName: string;
  purchaseDate: string;
  totalCost: number;
  items?: {
    productId: string;
    productName: string;
    quantity: number;
    price: number;
  }[];
}

// 时间过滤器类型
type TimeFilterType = 'month' | 'quarter' | 'year';

// 状态管理
const loading = ref(false);
const errorMessage = ref('');
let profitChart: Chart | null = null;
const activeTab = ref('sales'); // API明细标签页

// API数据
const apiSalesData = ref<SalesOrder[]>([]);
const apiCostData = ref<SupplierCost[]>([]);

// API 时间过滤器
const apiTimeFilter = reactive({
  type: 'month' as TimeFilterType,
  year: new Date().getFullYear(),
  month: new Date().getMonth() + 1,
  quarter: Math.ceil((new Date().getMonth() + 1) / 3),
});

// 报表数据
const reportData = reactive({
    totalIncome: 0,
    totalCost: 0,
    totalProfit: 0,
    incomeDetails: [] as IncomeItem[],
    profitStatus: 'profit' as 'profit' | 'loss'
});

// 可用的年份和月份
const availableYears = computed(() => {
  const currentYear = new Date().getFullYear();
  return [currentYear - 1, currentYear, currentYear + 1];
});

const availableMonths = computed(() => {
  return Array.from({length: 12}, (_, i) => i + 1);
});

// 重置API时间过滤器
const resetApiTimeFilter = () => {
  apiTimeFilter.year = new Date().getFullYear();
  
  if (apiTimeFilter.type === 'month') {
    apiTimeFilter.month = new Date().getMonth() + 1;
  } else if (apiTimeFilter.type === 'quarter') {
    apiTimeFilter.quarter = Math.ceil((new Date().getMonth() + 1) / 3);
  }
};

// 获取API模式下的时间周期显示
const getApiPeriodDisplay = () => {
  if (apiTimeFilter.type === 'month') {
    return `${apiTimeFilter.year}年${apiTimeFilter.month}月`;
  } else if (apiTimeFilter.type === 'quarter') {
    return `${apiTimeFilter.year}年第${apiTimeFilter.quarter}季度`;
  } else {
    return `${apiTimeFilter.year}年`;
  }
};

// API 模式：获取数据
const fetchApiData = async () => {
  loading.value = true;
  errorMessage.value = '';
  
  try {
    // 构建时间范围参数
    const timeRange = getApiTimeRange();
    
    // 1. 从销售模块获取销售数据
    const salesResponse = await axios.get<SalesOrder[]>('/api/sales/orders', {
      params: timeRange
    });
    
    // 2. 从供应商模块获取成本数据
    const costResponse = await axios.get<SupplierCost[]>('/api/suppliers/costs', {
      params: timeRange
    });
    
    // 存储原始数据
    apiSalesData.value = salesResponse.data;
    apiCostData.value = costResponse.data;
    
    // 计算总收入
    const totalIncome = apiSalesData.value.reduce(
      (sum, order) => sum + order.totalAmount,
      0
    );
    
    // 计算总成本
    const totalCost = apiCostData.value.reduce(
      (sum, cost) => sum + cost.totalCost,
      0
    );
    
    // 计算总利润
    const totalProfit = totalIncome - totalCost;
    
    // 构建收入明细
    const incomeDetails: IncomeItem[] = [
      { category: '商品销售', amount: totalIncome, percentage: 100 }
    ];
    
    // 更新报表数据
    reportData.totalIncome = totalIncome;
    reportData.totalCost = totalCost;
    reportData.totalProfit = totalProfit;
    reportData.incomeDetails = incomeDetails;
    reportData.profitStatus = totalProfit >= 0 ? 'profit' : 'loss';
    
    // 更新图表
    updateChart();
    
    errorMessage.value = `已成功获取${getApiPeriodDisplay()}的财务数据`;
    setTimeout(() => {
      errorMessage.value = '';
    }, 2000);
  } catch (error) {
    errorMessage.value = handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 获取API时间范围参数
const getApiTimeRange = () => {
  if (apiTimeFilter.type === 'month') {
    return {
      startDate: `${apiTimeFilter.year}-${apiTimeFilter.month.toString().padStart(2, '0')}-01`,
      endDate: `${apiTimeFilter.year}-${apiTimeFilter.month.toString().padStart(2, '0')}-31`
    };
  } else if (apiTimeFilter.type === 'quarter') {
    const startMonth = (apiTimeFilter.quarter - 1) * 3 + 1;
    const endMonth = apiTimeFilter.quarter * 3;
    const endDay = new Date(apiTimeFilter.year, endMonth, 0).getDate();
    
    return {
      startDate: `${apiTimeFilter.year}-${startMonth.toString().padStart(2, '0')}-01`,
      endDate: `${apiTimeFilter.year}-${endMonth.toString().padStart(2, '0')}-${endDay}`
    };
  } else {
    return {
      startDate: `${apiTimeFilter.year}-01-01`,
      endDate: `${apiTimeFilter.year}-12-31`
    };
  }
};

// 更新图表
const updateChart = () => {
  if (profitChart) {
    profitChart.destroy();
  }
  
  const ctx = document.getElementById('profitChart') as HTMLCanvasElement;
  if (!ctx || !reportData.incomeDetails.length) {
    return;
  }
  
  profitChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: reportData.incomeDetails.map(item => item.category),
      datasets: [{
        label: '收入金额',
        data: reportData.incomeDetails.map(item => item.amount),
        backgroundColor: 'rgba(75, 192, 192, 0.6)',
        borderColor: 'rgba(75, 192, 192, 1)',
        borderWidth: 1
      }, {
        label: '成本金额',
        data: [reportData.totalCost],
        backgroundColor: 'rgba(255, 99, 132, 0.6)',
        borderColor: 'rgba(255, 99, 132, 1)',
        borderWidth: 1
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: (value) => '¥' + value.toLocaleString()
          }
        }
      },
      plugins: {
        tooltip: {
          callbacks: {
            label: (context: TooltipItem<'bar'>) => {
              return context.dataset.label + ': ¥' + context.parsed.y.toLocaleString();
            }
          }
        }
      }
    }
  });
};

// 处理 API 错误
const handleApiError = (error: unknown) => {
  if (axios.isAxiosError(error)) {
    const axiosError = error as AxiosError;
    if (axiosError.response) {
      const errorData = axiosError.response.data as { message?: string };
      return `服务器错误 (${axiosError.response.status}): ${errorData.message || '未知错误'}`;
    } else if (axiosError.request) {
      return '无法连接到服务器，请检查网络连接';
    }
  }
  return `请求错误: ${(error as Error).message}`;
};

// 格式化货币
const formatCurrency = (value: number) => {
  return '¥' + value.toLocaleString();
};

// 生命周期钩子
onMounted(() => {
  // 初始获取数据
  fetchApiData();
});

onUnmounted(() => {
  // 清理图表
  if (profitChart) {
    profitChart.destroy();
  }
});
</script>

<style scoped>
.financial-module {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Inter', sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  color: #333;
  margin: 0;
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.subtitle {
  font-size: 20px;
  color: #555;
  margin-top: 0;
  margin-bottom: 15px;
}

.sub-subtitle {
  font-size: 18px;
  color: #777;
  margin-top: 25px;
  margin-bottom: 10px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.time-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

select, input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.report-period {
  font-size: 16px;
  color: #666;
}

.report-id {
  font-size: 14px;
  color: #888;
}

.status-tag {
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.status-tag.profit {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status-tag.loss {
  background-color: #ffebee;
  color: #c62828;
}

.report-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30px;
  padding: 15px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.summary-item {
  text-align: center;
}

.item-label {
  font-size: 14px;
  color: #777;
  margin-bottom: 5px;
}

.item-value {
  font-size: 20px;
  font-weight: 600;
}

.item-value.profit {
  color: #2e7d32;
}

.item-value.loss {
  color: #c62828;
}

.table-responsive {
  overflow-x: auto;
}

.details-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.details-table th, .details-table td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.details-table th {
  background-color: #f5f5f5;
  font-weight: 600;
}

.chart-container {
  height: 300px;
  margin-top: 20px;
}

.error-message {
  background-color: #ffebee;
  color: #c62828;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.error-message i {
  margin-right: 10px;
}

.error-text {
  color: #c62828;
  font-size: 12px;
  margin-top: 5px;
}

.details-tabs {
  display: flex;
  margin-bottom: 20px;
}

.details-tabs button {
  background-color: #f5f5f5;
  color: #555;
  border: 1px solid #ddd;
  border-radius: 4px 4px 0 0;
  margin-right: 5px;
  padding: 10px 15px;
}

.details-tabs button.active {
  background-color: #fff;
  border-bottom: 1px solid #fff;
  color: #4CAF50;
  font-weight: 500;
}

.tab-content {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 0 4px 4px 4px;
  margin-top: -1px;
}

.summary {
  display: flex;
  align-items: center;
  margin-top: 15px;
  font-weight: 500;
}

.summary .label {
  margin-right: 10px;
  color: #777;
}

.summary .value {
  color: #333;
}
</style>